package pers.mihao.quickstream.account.service.impl;

import org.springframework.stereotype.Service;
import pers.mihao.quickstream.account.manager.AccountManager;
import pers.mihao.quickstream.account.model.dto.AccountDTO;
import pers.mihao.quickstream.account.model.dto.PlatformDTO;
import pers.mihao.quickstream.account.model.vo.Account;
import pers.mihao.quickstream.account.model.vo.Platform;
import pers.mihao.quickstream.account.repository.AccountRepository;
import pers.mihao.quickstream.account.repository.PlatformRepository;
import pers.mihao.quickstream.account.service.AccountService;
import pers.mihao.quickstream.common.model.ApiPageDTO;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author mihao
 * @since 2024/11/24
 */
@Service
public class AccountServiceImpl implements AccountService {

    @Resource
    AccountRepository accountRepository;

    @Resource
    PlatformRepository platformRepository;

    @Override
    public List<Account> listAllAccountByUserId(Long userId) {
        ApiPageDTO apiPageDTO = new ApiPageDTO();
        apiPageDTO.setUserId(userId);
        apiPageDTO.setPageStart(1);
        apiPageDTO.setPageSize(100);
        List<AccountDTO> accountDTOS = accountRepository.queryAccountByUserIdWithPage(apiPageDTO);

        return Optional.ofNullable(accountDTOS).orElse(new ArrayList<>())
                .stream().map(this::map2Account).collect(Collectors.toList());
    }

    @Override
    public Account queryAccountById(Long accountId) {
        AccountDTO accountDTO = accountRepository.queryById(accountId);
        return map2Account(accountDTO);
    }

    private Account map2Account(AccountDTO accountDTO) {
        if (accountDTO == null) {
            return null;
        }
        PlatformDTO platformDTO = platformRepository.queryByCode(accountDTO.getPlatformCode());
        Platform platform = new Platform();
        platform.setCode(platformDTO.getPlatformCode());
        platform.setName(platformDTO.getPlatformName());
        Account account = new Account();
        account.setAccountId(accountDTO.getId());
        account.setUserId(accountDTO.getSourceUserId());
        account.setPlatform(platform);
        return account;
    }
}
